package com.example.demo.controller

import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.*

@Controller
@RequestMapping("/api")
class DemoController {
    @RequestMapping('/hello')
    @ResponseBody
    String hello() {
        return 'Hello World'
    }

    @RequestMapping(value = ['/index', '/main', '/'], method = RequestMethod.GET)
    @ResponseBody
    String index1() {
        return 'Hello World'
    }

    @RequestMapping(value = '/get', method = RequestMethod.GET)
    @ResponseBody
    String get() {
        return 'GET请求'
    }

    @RequestMapping(value = '/post', method = RequestMethod.POST)
    @ResponseBody
    String post() {
        return 'POST请求'
    }

    @RequestMapping('/param1')
    @ResponseBody
    String param1(@RequestParam("name") String name) {
        return "你的用户名是$name"
    }

    @RequestMapping(value = '/param2', params = ['age', 'name'])
    @ResponseBody
    String param2(@RequestParam("name") String name, @RequestParam("age") int age) {
        return "你的用户名是$name，年龄是$age"
    }

    @RequestMapping('/param3')
    @ResponseBody
    String param3(@RequestParam(value = 'name', defaultValue = 'defaultValue') String name) {
        return "你的用户名是$name"
    }

    @RequestMapping(value = '/json1', consumes = ['application/json'])
    @ResponseBody
    String json1() {
        return '主页'
    }

    @RequestMapping('/json2')
    @ResponseBody
    String json2(@RequestBody List<String> usernames) {
        StringBuilder users = new StringBuilder()
        usernames.each { user ->
            users.append(user).append('\n')
        }
        return users.toString()
    }

    @RequestMapping('/path/{name}')
    @ResponseBody
    String index(@PathVariable('name') String username) {
        return "你的用户名是$username"
    }
}
